#include "qtc_alarm_core/AlarmTable.h"
#include <QtCore/QJsonValue>

namespace qtc_alarm_core {

void AlarmTable::applyStateJson(const QString& pv, const QJsonObject& obj) {
    auto& row = rows[pv];
    row.pv = pv;
    row.severity = obj.value("severity").toString(row.severity);
    row.message = obj.value("message").toString(row.message);
    // Some payloads may use 'value' as string or number
    const auto v = obj.value("value");
    if (v.isString()) row.value = v.toString();
    else if (v.isDouble()) row.value = QString::number(v.toDouble());
    // Time may be 'time' ISO or 'time' ms; assume ms in 'time_epoch_ms' or numeric 'time'
    if (obj.contains("time_epoch_ms")) {
        row.time_epoch_ms = obj.value("time_epoch_ms").toVariant().toLongLong();
    } else if (obj.contains("time")) {
        row.time_epoch_ms = obj.value("time").toVariant().toLongLong();
    }
    // optional
    if (obj.contains("acknowledged")) {
        row.acknowledged = obj.value("acknowledged").toBool(row.acknowledged);
    }
}

QJsonArray AlarmTable::toJsonArray() const {
    QJsonArray arr;
    for (const auto& pv : rows.keys()) {
        arr.append(rows[pv].toJson());
    }
    return arr;
}

} // namespace qtc_alarm_core